<?php
namespace app\controller;

use app\BaseController;
use think\Request;
use app\model\LearningRecord;
use app\model\ScoreDetail;
use app\model\CourseOutline;
use app\model\TeachingPlan;
use app\model\TeachingPlanElement;
use think\facade\Db;

class LearningRecordController extends BaseController
{
    /**
     * 获取学习记录列表
     */
    public function index(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $page = $request->param('page', 1);
        $pageSize = $request->param('page_size', 10);
        $status = $request->param('status');
        $type = $request->param('learning_type');

        $query = LearningRecord::where('user_id', $user->id)
            ->with(['course', 'teachingPlan']);

        if (isset($status)) {
            $query->where('status', $status);
        }
        if (isset($type)) {
            $query->where('learning_type', $type);
        }

        $records = $query->order('created_at', 'desc')
            ->paginate([
                'list_rows' => $pageSize,
                'page' => $page
            ]);

        return json([
            'status' => 200,
            'data' => [
                'total' => $records->total(),
                'current_page' => $records->currentPage(),
                'last_page' => $records->lastPage(),
                'records' => $records->items()
            ]
        ]);
    }

    /**
     * 创建学习记录
     */
    public function create(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $data = $request->post();
        
        // 验证必填字段
        if (empty($data['learning_type'])) {
            return json(['status' => 400, 'message' => '请选择学习类型']);
        }
        if (empty($data['course_id']) && empty($data['teaching_plan_id'])) {
            return json(['status' => 400, 'message' => '请选择课程或教案']);
        }

        Db::startTrans();
        try {
            // 获取初始教案和元素ID
            if (!empty($data['course_id'])) {
                $course = CourseOutline::find($data['course_id']);
                if (!$course) {
                    return json(['status' => 404, 'message' => '课程不存在']);
                }
                $firstPlanId = $course->teaching_plan_ids[0] ?? null;
                $firstPlan = TeachingPlan::find($firstPlanId);
            } else {
                $firstPlan = TeachingPlan::find($data['teaching_plan_id']);
            }

            if (!$firstPlan) {
                return json(['status' => 404, 'message' => '教案不存在']);
            }

            // 获取第一个元素
            $firstElement = TeachingPlanElement::where('plan_id', $firstPlan->id)
                ->order('sort_order', 'asc')
                ->find();

            $record = new LearningRecord;
            $record->user_id = $user->id;
            $record->course_id = $data['course_id'] ?? null;
            $record->teaching_plan_id = $data['teaching_plan_id'] ?? null;
            $record->current_plan_id = $firstPlan->id;
            $record->current_element_id = $firstElement ? $firstElement->id : null;
            $record->learning_type = $data['learning_type'];
            $record->status = LearningRecord::STATUS_IN_PROGRESS;
            $record->last_study_at = time();
            $record->save();

            Db::commit();
            return json([
                'status' => 200,
                'message' => '学习记录创建成功',
                'data' => $record
            ]);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 500, 'message' => '创建失败：' . $e->getMessage()]);
        }
    }

    /**
     * 更新学习记录
     */
    public function update(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $recordId = $request->param('id');
        $data = $request->post();

        $record = LearningRecord::where('id', $recordId)
            ->where('user_id', $user->id)
            ->find();

        if (!$record) {
            return json(['status' => 404, 'message' => '学习记录不存在或无权限']);
        }

        try {
            $updateData = [];
            if (isset($data['current_plan_id'])) {
                $updateData['current_plan_id'] = $data['current_plan_id'];
            }
            if (isset($data['current_element_id'])) {
                $updateData['current_element_id'] = $data['current_element_id'];
            }
            if (isset($data['progress_rate'])) {
                $updateData['progress_rate'] = $data['progress_rate'];
            }
            if (isset($data['status'])) {
                $updateData['status'] = $data['status'];
            }
            
            $updateData['last_study_at'] = time();
            $record->save($updateData);

            return json(['status' => 200, 'message' => '更新成功']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '更新失败：' . $e->getMessage()]);
        }
    }

    /**
     * 记录得分
     */
    public function recordScore(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $recordId = $request->param('id');
        $data = $request->post();

        if (empty($data['element_id']) || !isset($data['achieved_score'])) {
            return json(['status' => 400, 'message' => '请提供完整的得分信息']);
        }

        $record = LearningRecord::where('id', $recordId)
            ->where('user_id', $user->id)
            ->find();

        if (!$record) {
            return json(['status' => 404, 'message' => '学习记录不存在或无权限']);
        }

        Db::startTrans();
        try {
            // 记录得分详情
            $scoreDetail = new ScoreDetail;
            $scoreDetail->user_id = $user->id;
            $scoreDetail->learning_record_id = $recordId;
            $scoreDetail->element_id = $data['element_id'];
            $scoreDetail->message_id = $data['message_id'] ?? null; // 新增消息ID字段
            $scoreDetail->question_score = $data['question_score'] ?? 0;
            $scoreDetail->passing_score = $data['passing_score'] ?? 0;
            $scoreDetail->achieved_score = $data['achieved_score'];
            $scoreDetail->score_description = $data['score_description'] ?? '';
            $scoreDetail->answer_content = $data['answer_content'] ?? '';
            $scoreDetail->is_passed = $data['achieved_score'] >= ($data['passing_score'] ?? 0) ? 1 : 0;
            $scoreDetail->answer_time = time();
            $scoreDetail->save();

            // 更新学习记录的总分
            $totalScore = ScoreDetail::where('learning_record_id', $recordId)
                ->sum('achieved_score');
            
            $record->achieved_score = $totalScore;
            $record->save();

            Db::commit();
            return json(['status' => 200, 'message' => '得分记录成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 500, 'message' => '记录失败：' . $e->getMessage()]);
        }
    }

    /**
     * 重置学习记录
     */
    public function reset(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $recordId = $request->param('id');

        $record = LearningRecord::where('id', $recordId)
            ->where('user_id', $user->id)
            ->find();

        if (!$record) {
            return json(['status' => 404, 'message' => '学习记录不存在或无权限']);
        }

        Db::startTrans();
        try {
            // 获取初始教案和元素ID
            if ($record->course_id) {
                $course = CourseOutline::find($record->course_id);
                $firstPlanId = $course->teaching_plan_ids[0] ?? null;
                $firstPlan = TeachingPlan::find($firstPlanId);
            } else {
                $firstPlan = TeachingPlan::find($record->teaching_plan_id);
            }

            // 获取第一个元素
            $firstElement = TeachingPlanElement::where('plan_id', $firstPlan->id)
                ->order('sort_order', 'asc')
                ->find();

            // 重置记录
            $record->current_plan_id = $firstPlan->id;
            $record->current_element_id = $firstElement ? $firstElement->id : null;
            $record->progress_rate = 0;
            $record->achieved_score = 0;
            $record->status = LearningRecord::STATUS_IN_PROGRESS;
            $record->last_study_at = time();
            $record->save();

            // 删除所有得分记录
            ScoreDetail::where('learning_record_id', $recordId)->delete();

            Db::commit();
            return json(['status' => 200, 'message' => '学习记录已重置']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status' => 500, 'message' => '重置失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取学习记录详情
     */
    public function detail(Request $request)
    {
        $user = UserController::getUserFromToken($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $recordId = $request->param('id');
        
        try {
            $record = LearningRecord::with(['course', 'teachingPlan', 'scoreDetails'])
                ->where('id', $recordId)
                ->where('user_id', $user->id)
                ->find();

            if (!$record) {
                return json(['status' => 404, 'message' => '学习记录不存在']);
            }

            return json([
                'status' => 200,
                'data' => $record
            ]);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '获取失败：' . $e->getMessage()]);
        }
    }
} 